# LLMTourMapGenApp/views.py
from django.http import JsonResponse
from .LLMTourMapGenFuncs.LLMGetStartAndEnd import parse_locations
from django.views.decorators.csrf import csrf_exempt
from .models import MapExport
import json


@csrf_exempt
def process_navigation_request(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_input = str(data.get('text', ''))
            history = data.get('history', [])  # 新增历史记录获取

            # 修改调用方式传递历史记录
            result = parse_locations(user_input, history)

            try:
                result_json = json.loads(result)
            except json.JSONDecodeError:
                # 添加错误处理
                return JsonResponse({
                    'status': 'error',
                    'advice': '系统响应格式异常，请尝试重新输入'
                })

            request.session['current_json'] = result_json  # 将当前生成的数据存入session

            return JsonResponse(result_json)
        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'advice': f'系统处理异常：{str(e)}'
            })
    return JsonResponse({'status': 'invalid_request'})


@csrf_exempt
def export_map(request):
    if request.method == 'POST':
        current_json = request.session.get('current_json')
        if not current_json:
            return JsonResponse({'error': '没有可导出的数据'}, status=400)

        # 创建持久化存储
        export = MapExport.objects.create(json_data=current_json)

        # 生成访问URL（需要配置WebApp的路由）
        export_url = f"/export/{export.id}/"

        return JsonResponse({'url': export_url})
    return JsonResponse({'error': '无效请求方法'}, status=405)
